<template>
    <div class="app-container">
        <div class="contentBox">
            <div class="searchBox">
                <el-form :model="queryParams" ref="queryRef" :inline="true" @submit.prevent>
                    <el-form-item prop="name" style="margin: 0 6px 0 0;">
                        <el-input
                            class="inputBox"
                            v-model="queryParams.name"
                            placeholder="请输入分类名称"
                            clearable
                            @keyup.enter="handleQuery()"
                        />
                    </el-form-item>
                    <el-form-item style="margin: 0 6px 0 0;">
                        <el-button class="normalFormBg searchBtn" icon="Search" @click="handleQuery()"></el-button>
                        <el-button class="normalFormBg searchBtn" icon="Refresh" @click="resetQuery"></el-button>
                        <el-button type="primary" icon="DArrowLeft" @click="handlePreQuery" v-if="searchList.length > 1">上一级区域</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <el-row :gutter="10" style="margin: 16px 0;">
                <el-col :span="1.5">
                    <div class="normalBtn pageFlex pageFlexCenter" v-hasPermi="['gasManage:stockManage:goodCategory:add']"
                        @click="handleAdd()">
                        <img src="@/assets/images/plus.png" class="normalBtn_icon">
                        <div class="normalBtn_text">新增</div>
                    </div>
                </el-col>
            </el-row>
            <el-table
                v-loading="loading"
                :data="dataList"
                border>
                <el-table-column prop="id" label="分类ID" width="100" :show-overflow-tooltip="true" fixed="left"></el-table-column>
                <el-table-column prop="name" label="分类名称" width="200" :show-overflow-tooltip="true">
                  <template #default="scope">
                    <div style="color: var(--el-color-primary);max-width: 180px;cursor: pointer;" class="textOverflow1" @click="handleQuery(scope.row.id, scope.row.name)">{{ scope.row.name }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="cover" label="分类图标" width="80" align="center">
                  <template #default="scope">
                    <div class="tableImgBox1">
                      <el-image class="img" fit="contain" lazy :src="setCoverUrl(scope.row.cover)"
                        @click="handlePreviewShow(setCoverUrl(scope.row.cover))" v-if="scope.row.cover" />
                      <div class="emptyBox" v-else>暂无图标</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="isEnable" label="状态" width="150">
                  <template #default="scope">
                    <div v-for="(item, index) in system_open_status" :key="index" v-show="item.value == scope.row.isEnable">
                      <el-tag :type="item.elTagType" v-if="item.elTagType">{{ item.label }}</el-tag>
                      <div v-else>{{ item.label }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="remarks" label="备注说明" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column label="操作" width="340" align="center" fixed="right">
                    <template #default="scope">
                        <div class="pageFlex pageFlexCenter" style="width: 100%;">
                            <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:goodCategory:list']"
                                 @click="handleInfo(scope.row.id)">
                              <img src="@/assets/images/fileManage.png" class="img">
                              <div class="text">详情</div>
                            </div>
                            <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:goodCategory:add']"
                                 @click="handleAdd(scope.row.id, scope.row.name)">
                              <img src="@/assets/images/add.png" class="img">
                              <div class="text">新增</div>
                            </div>
                            <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:goodCategory:edit']"
                                @click="handleEdit(scope.row.id)">
                                <img src="@/assets/images/edit.png" class="img">
                                <div class="text">修改</div>
                            </div>
                            <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:goodCategory:delete']"
                                @click="handleDelete(scope.row)">
                                <img src="@/assets/images/delete.png" class="img">
                                <div class="text">删除</div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <template #empty>
                  <el-empty description="暂无数据"/>
                </template>
            </el-table>
            <div class="pageFlex pageAlignCenter pageSpaceBetween" style="margin-top: 20px;">
                <div class="totalText">共计 {{total}} 条</div>
            </div>
        </div>
        <el-drawer v-model="modalShow" direction="rtl" size="600" :title="modalTitle">
          <div class="modalBox">
            <div class="modalBoxContent">
              <el-form
                  ref="formRef"
                  class="formContent"
                  label-width="80"
                  :model="form"
                  :rules="rules"
                  :disabled="modalTitle === '分类详情'"
              >
                <div class="formContentTop pageFlex pageAlignCenter">
                  <div class="line"></div>
                  <div class="title">分类信息</div>
                </div>
                <div class="formContentCenter bgFF">
                  <el-form-item label="上级分类" prop="parentId">
                    <SelectOption class="selectOptionBox" ref="typeSelectOption" placeHolder="请选择类型" title="类型选择"
                        v-model="form.parentId" :defaultFormValue="typeDefault" :disabled="modalTitle === '分类详情'"
                        @loadOptions="typeDataLoad" @chooseError="chooseTypeError" v-if="modalShow && !formLoading"/>
                  </el-form-item>
                  <el-form-item label="分类图标" prop="cover">
                    <div class="imgBox">
                      <ImageUpload ref="cover" v-model="form.cover" bg="#FFFFFF" v-if="modalShow"></ImageUpload>
                    </div>
                  </el-form-item>
                  <el-form-item label="分类名称" prop="name">
                    <el-input
                        class="inputBox"
                        v-model="form.name"
                        placeholder="请输入分类名称"
                        clearable
                    />
                  </el-form-item>
                  <el-form-item label="首字母" prop="initials">
                    <el-input
                        class="inputBox"
                        v-model="form.initials"
                        placeholder="请输入首字母"
                        clearable
                    />
                  </el-form-item>
                  <el-form-item label="排序" prop="sort">
                    <el-input
                        class="inputBox"
                        type="number"
                        v-model="form.sort"
                        placeholder="请输入排序"
                        clearable
                    />
                  </el-form-item>
                  <el-form-item label="备注说明" prop="remarks">
                    <el-input
                        class="textareaBox"
                        v-model="form.remarks"
                        type="textarea"
                        placeholder="请输入备注说明"
                    />
                  </el-form-item>
                  <el-form-item label="状态" prop="isEnable">
                    <el-radio-group v-model="form.isEnable">
                      <el-radio
                          v-for="dict in system_open_status"
                          :key="dict.value"
                          :value="dict.value"
                      >{{ dict.label }}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-form>
            </div>
            <div class="lineBox" v-if="modalTitle !== '分类详情'"></div>
            <div class="bottomBox pageFlex pageFlexCenter" v-if="modalTitle !== '分类详情'">
              <el-button type="primary" :loading="submitLoading" @click="submitNow">确认提交</el-button>
            </div>
            <el-button type="primary" :loading="formLoading" class="modalLoadingBox" v-if="formLoading">加载数据中</el-button>
          </div>
        </el-drawer>
        <el-image-viewer :url-list="srcList" @close="handlePreviewClose" v-if="showPreview"/>
    </div>
</template>
<script setup>
import { onMounted, computed } from 'vue';
import {ElLoading, ElMessageBox} from 'element-plus';
import ImageUpload from '@/views/gasManage/components/ImageUpload';
import SelectOption from '@/views/gasManage/components/SelectOption';
import { searchCategoryApi, addCategoryApi, searchCategoryByIdApi, editCategoryApi, deleteCategoryApi } from '@/api/gasManage/stockManage/goodCategory';
const { proxy } = getCurrentInstance();
const { system_open_status } = proxy.useDict("system_open_status");
const baseUrl = import.meta.env.VITE_APP_BASE_API;
// -----------------------------------查询-----------------------------------
const queryParams = ref({
    parentId: 0,
    name: ''
})
const loading = ref(false);
const total = ref(0);
const dataList = ref([]);
const searchList = ref([{
  id: 0,
  name: '主分类'
}])
const setCoverUrl = computed(()=>{
  return url => {
    if(url){
      return baseUrl+url
    }
    return  ''
  }
})
function handleQuery(id, name) {
  if(id){
    searchList.value.push({id: Number(id), name});
  }
  getList();
}
function resetQuery(){
  proxy.resetForm("queryRef");
  handleQuery();
}
function handlePreQuery(){
  searchList.value.splice(searchList.value.length - 1, 1);
  handleQuery();
}
async function getList(){
  loading.value = true;
  queryParams.value.parentId = searchList.value[searchList.value.length - 1].id;
  let data = await goodsCategoryApi(queryParams.value);
  if(data && Array.isArray(data)) {
    dataList.value = data;
  }else{
    dataList.value = [];
  }
  loading.value = false;
}
function goodsCategoryApi(params){
  return new Promise(resolve => {
    searchCategoryApi(params).then(res => {
      total.value = Number(res.total);
      resolve(Array.isArray(res.rows) ? res.rows : []);
    }).catch(() => {resolve(false)})
  })
}
// -----------------------------------查看图片-----------------------------
const showPreview = ref(false);
const srcList = ref([])
function handlePreviewShow(link){
  srcList.value = [link];
  showPreview.value = true;
}
function handlePreviewClose(){
  showPreview.value = false;
  srcList.value = [];
}
// ----------------------------弹窗-------------------------------
const modalShow = ref(false);
const modalTitle = ref('');
const formLoading = ref(false);
const submitLoading = ref(false);
const form = ref({
  parentId: '',
  cover: '',
  name: '',
  initials: '',
  sort: '',
  remarks: '',
  isEnable: '1'
})
const rules = ref({
  parentId: [{ required: true, message: "上级分类未上传", trigger: "blur" }],
  cover: [{ required: true, message: "分类图标未上传", trigger: "blur" }],
  name: [{ required: true, message: "分类名称不能为空", trigger: "blur" }],
  initials: [{ required: true, message: "首字母不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
});
function handleModalShow(name){
  modalTitle.value = name;
  modalShow.value = true;
}
function handleModalHide(){
  modalShow.value = false;
}
async function setFormData(id){
  formLoading.value = true;
  let data = await getCategoryDataApi(id);
  if(data){
    form.value.id = data.id;
    form.value.cover = data.cover;
    form.value.name = data.name;
    form.value.initials = data.initials;
    form.value.sort = data.sort;
    form.value.remarks = data.remarks;
    form.value.isEnable = String(data.isEnable);
    form.value.parentId = data.parentId == 0 ? data.parentId : Number(data.parentId);
  }
  formLoading.value = false;
}
function getCategoryDataApi(id){
  return new Promise(resolve => {
    searchCategoryByIdApi(id).then(res => {
      resolve(res.data);
    }).catch(()=>{
      resolve(false);
    })
  })
}
function submitNow(){
  if(submitLoading.value) return;
  proxy.$refs["formRef"].validate(valid => {
    if(valid){
      submitLoading.value = true;
      if(modalTitle.value === '新增分类'){
        addNow();
      }else{
        editNow();
      }
    }else{
      proxy.$modal.alertWarning('信息填写有误，请查看！');
    }
  })
}
// ----------------------------选择类型----------------------------
const typeDefault = ref('');
async function typeDataLoad(e){
  const { node, resolve } = e;
  let data = [];
  if(node.level === 0){
    data = [{
      id: String(0),
      name: '主分类'
    }]
  }else{
    data = await goodsCategoryApi({parentId: node.data.id});
  }
  proxy.$refs.typeSelectOption.handleLoadApi(data, node, resolve);
}
function chooseTypeError(e){
  proxy.$modal.msgError(e.msg);
}
// ----------------------------详情-------------------------------
function handleInfo(id){
  typeDefault.value = searchList.value[searchList.value.length - 1].name;
  handleModalShow('分类详情');
  setFormData(id);
}
// ----------------------------修改-------------------------------
function handleEdit(id){
  typeDefault.value = searchList.value[searchList.value.length - 1].name;
  handleModalShow('修改分类信息');
  setFormData(id);
}
function editNow(){
  editCategoryApi(form.value).then(() => {
    submitLoading.value = false;
    handleModalHide();
    proxy.$modal.msgSuccess('修改分类信息成功');
    getList();
  }).catch(()=>{
    submitLoading.value = false;
  })
}
// ----------------------------新增-------------------------------
function handleAdd(id, name){
  proxy.resetForm('formRef');
  typeDefault.value = '';
  if(id){
    typeDefault.value = name;
    form.value.parentId = id == 0 ? 0 : Number(id);
  }
  handleModalShow('新增分类');
}
function addNow(){
  addCategoryApi(form.value).then(() => {
    submitLoading.value = false;
    handleModalHide();
    proxy.$modal.msgSuccess('新增分类成功');
    getList();
  }).catch(()=>{
    submitLoading.value = false;
  })
}
// ----------------------删除-------------------------
function handleDelete(row){
  ElMessageBox.confirm(`确认删除分类名称为【${row.name}】的数据`,'提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteNow(row);
  }).catch(() => {})
}
async function deleteNow(row){
  const loading = ElLoading.service({
    lock: true,
    text: '删除中~',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  let data = await goodsCategoryApi({parentId: row.id});
  if(data.length){
    loading.close();
    proxy.$modal.msgError(row.name+'存在子分类，因此不可删除！');
  }else{
    deleteCategoryApi(row.id).then(()=>{
      loading.close();
      proxy.$modal.msgSuccess(row.name+'分类删除成功');
      getList();
    }).catch(()=>{
      loading.close();
    })
  }
}
onMounted(()=>{
    getList();
})
</script>
<style lang='scss' scoped>
@import "@/assets/styles/public.scss";
:deep(.el-input){
  .el-input__wrapper{
    background-color: $formBgSet;
    box-shadow: none;
  }
}
.treeBox{
  min-width: 360px;
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 5;
  padding: 0 5px 10px 0px;
  font-size: 12px;
  border-radius: 4px;
  border: 1px solid var(--el-border-color-light);
  box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
  .treeBoxTitle{
    padding: 10px;
    font-size: 15px;
    font-weight: 600;
  }
}
.normalBtn{
    &_icon2{
        margin-right: 10px;
        color: $normalBtnColor;
    }
}
.loadingBox{
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, .7);
  border: 1px solid transparent;
  box-shadow: none;
  border-radius: 0px;
  position: absolute;
  top: 0;
  left: 0;
}
.app-container{
    width: 100%;
    min-height: calc(100vh - 66px);
    background: #F8F8F9;
}
.tableImg{
  width: 80px;
  height: 80px;
  background-color: $formBgSet;
}
.contentBox{
    width: 100%;
    min-height: $pageMinHeight;
    background-color: #FFFFFF;
    border-radius: 5px;
    box-sizing: border-box;
    padding: 12px;
    .searchBtn{
        width: 32px;
        height: 32px;
        font-size: 12px;
        padding: 0;
        border: none;
        margin: 0 6px 0 0px;
    }
    .btnSetBox{
        padding: 0 10px;
        box-sizing: border-box;
        border-right: 1px solid $borderColor;
        cursor: pointer;
        .text{
            height: 16px;
            line-height: 16px;
            color: var(--el-color-primary);
        }
        .img{
            width: 16px;
            height: 16px;
            margin-right: 2px;
        }
        &:last-child{
            border-right: none;
        }
    }
    .totalText{
        height: 22px;
        font-weight: 400;
        font-size: 14px;
        color: #1D2129;
        line-height: 22px;
    }
}
:deep(.el-drawer){
  .el-drawer__header{
    margin: 0;
    padding-bottom: 20px;
  }
  .el-drawer__body{
    padding: 0;
  }
}
</style>